#!/bin/bash

mk_dir="/home/fox/sdk/foxprj/default/example"

pre_command() {
    config_entries=(
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/configs    luckfox_rv1106_linux_defconfig"
        "/home/fox/sdk/project/cfg/BoardConfig_IPC              BoardConfig-SPI_NAND-Buildroot-RV1103_Luckfox_Pico_Mini_B-IPC.mk"
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/boot/dts   rv1103g-luckfox-pico-mini.dts"
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/boot/dts   rv1103-luckfox-pico-ipc.dtsi"
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/boot/dts   rv1106-evb.dtsi"
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/boot/dts   rv1103.dtsi"
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/boot/dts   rv1106.dtsi"
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/boot/dts   rv1106-amp.dtsi"
        "/home/fox/sdk/sysdrv/source/kernel/arch/arm/boot/dts   rv1106-luckfox-pico-pi-ipc.dtsi"      
        "/home/fox/sdk/sysdrv/tools/board/buildroot             luckfox_pico_defconfig" 
    )

    for entry in "${config_entries[@]}"; do
        target_dir="${mk_dir}/${entry%% *}" 
        filename="${entry#* }" 
        
        target_dir=$(echo "$entry" | awk '{print $1}')
        filename=$(echo "$entry" | awk '{print $2}')
        
        source_file="${mk_dir}/${filename}"
        target_file="${target_dir}/${filename}"

        if [[ ! -f "$source_file" ]]; then
            echo "[ERROR***] source file do not exist: $source_file" >&2
            if ! cp -vp "$target_file" "$mk_dir/"; then
                echo "[ERROR***] fail to cp source file,please check!!!: $target_dir -> $source_file" >&2
                exit 1
            fi
            exit 1
        fi

        if [[ ! -d "$target_dir" ]]; then
            echo "[ERROR] target dir do not exist: $target_dir" >&2
            exit 1
        fi

        if [[ -f "$target_file" ]]; then
            if ! cp -v "$target_file" "${target_file}.old"; then
                echo "[ERROR] fail to bakup: $target_file" >&2
                exit 1
            fi
        else
            echo "[WARNING] fail to backup,file do not exist: $target_file"
        fi

        if ! cp -vp "$source_file" "$target_dir/"; then
            echo "[ERROR] fail to cp: $source_file -> $target_dir/" >&2
            exit 1
        fi

        echo "[INFO] success++++++++++++++++++++++++++++: $target_file"
    done

    echo "[SUCCESS] all done"
    return 0
}

case "$1" in
    pre)
        pre_command
        ;;
    build)
        /home/fox/sdk/build.sh
        ;;
    all)
        pre_command && /home/fox/sdk/build.sh       
        ;;
    *)
        echo "Usage: $0 {pre|build|all}"
        exit 1
        ;;
esac

exit $?